// import { build } from 'vite'
import webpack from "webpack";
import { writeFileSync, readFileSync } from "fs";
import { resolve } from "path";
import chalk from "chalk";

// 项目根目录
const rootDir = process.cwd();

const log = console.log;

const distBuild = async ({ env }, doneHandler) => {
  const simEnv = env === "development" ? "dev" : "prod";

  // bugfix: 如果使用import方式会导致webpack.base.js中的获取current.json逻辑提前执行
  const webpackConfig = await import(`../config/webpack.${simEnv}.js`);
  const compiler = webpack(webpackConfig.default);

  compiler.run((err, stats) => {
    if (err) {
      log(chalk.red(err.stack || err));
      if (err.details) {
        log(chalk.red(err.details));
      }
      doneHandler();
      return;
    }

    const info = stats.toString({
      colors: true,
    });

    log(info);

    if (stats.hasErrors()) {
      log(chalk.red(info.errors));
    }

    if (stats.hasWarnings()) {
      console.warn(info.warnings);
    }

    // log(stats.toString({
    //   colors: true,
    //   modules: false,
    //   children: false,
    //   chunks: false,
    //   chunkModules: false
    // }))

    const distCubeModulePath = resolve(rootDir, "dist", "CubeModule.json");
    const appFilePath = resolve(rootDir, "version", "app.json");

    const data = readFileSync(appFilePath);
    const config = JSON.parse(data);
    writeFileSync(distCubeModulePath, JSON.stringify(config.app));

    compiler.close((closeErr) => {
      if (!closeErr) {
        doneHandler();
        return;
      }
      log(chalk.red(closeErr));
      doneHandler();
    });
  });
};

export default distBuild;
